<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of ProductClass
 *
 * @author Windy
 */
class Product_ProductController extends Zend_Controller_Action {

    public function init() {
        
    }

    /** ------------------ Frontend Action ---------------------------------- * */

    /**
     * List product in given category
     *
     * @return void
     */
    public function categoryAction() {
        $request = $this->getRequest();
        $categoryId = $request->getParam('id');
        $pageIndex = $request->getParam('page_index', 1);
        $perPage = 6;
        $offset = ($pageIndex - 1) * $perPage;

        $categoryModel = Rabbit_Model_Factory::getInstance()->setModule('category')->getCategoryModel();
        $category = $categoryModel->getById($categoryId);

        if (null == $category) {
            throw new Tomato_Exception_NotFound();
        }

        /**
         * Add RSS link
         */
//        $this->view->headLink(array(
//            'rel' => 'alternate',
//            'type' => 'application/rss+xml',
//            'title' => 'RSS',
//            'href' => $this->view->url($category->getProperties(), 'product_rss_category'),
//        ));

        /**
         * Add meta keyword tag
         */
        if ($category->meta_keywords) {
            $keywords = strip_tags($category->meta_keywords);
            $this->view->headMeta()->setName('keywords', $keywords);
        }

        /**
         * Add meta description tag
         */
        if ($category->meta_description) {
            $description = strip_tags($category->meta_description);
            $this->view->headMeta()->setName('description', $description);
        }

        /**
         * Add title
         */
        if ($category->meta_title) {
            $this->view->headTitle($category->meta_title, 'SET');
        } else {
            $this->view->headTitle($category->name, 'SET');
        }

        $productModel = Rabbit_Model_Factory::getInstance()->setModule('product')->getProductModel();
        $products = $productModel->getByCategory($categoryId, $offset, $perPage);
        $numProducts = $productModel->count(array('status' => 'actived', 'category_id' => $categoryId));
//
//        /**
//         * Paginator
//         */
        $paginator = new Zend_Paginator(new Tomato_Utility_PaginatorAdapter($products, $numProducts));
        $paginator->setCurrentPageNumber($pageIndex);
        $paginator->setItemCountPerPage($perPage);

        $this->view->assign('products', $products);
        $this->view->assign('category', $category);
        $this->view->assign('pageIndex', $pageIndex);
        $this->view->assign('paginator', $paginator);
        $properties = $category->getProperties();
        $properties['category_id'] = $properties['id'];
        $this->view->assign('paginatorOptions', array(
            'path' => $this->view->url($properties, 'product_product_category'),
            'itemLink' => 'page-%d',
        ));
    }

    /**
     * View product details
     *
     * @return void
     */
    public function detailsAction() {

        $request = $this->getRequest();
        $productId = $request->getParam('id');
        $categoryId = $request->getParam('category_id');
//        $preview = $request->getParam('preview');
//        $preview = ($preview == 'true') ? true : false;

        /**
         * If user are going to preview product
         * @since 2.0.4
         */
//        if ($preview) {
//            $revisionId = $request->getParam('revision');
//            if ($revisionId) {
//                $this->_forward('preview', 'product', 'product', array('revision_id' => $revisionId));
//                return;
//            }
//        }


        $productModel = Rabbit_Model_Factory::getInstance()->setModule('product')->getproductModel();
        $product = $productModel->getById($productId);

        if (null == $product || ($product->status != 'actived' )) {//&& !$preview
            throw new Exception('Not found product with Id of ' . $productId);
        }

        /**
         * Add meta keywords
         */
        if ($product->meta_keywords) {
            $this->view->headMeta($product->meta_keywords, "keywords", 'name', array(), 'SET');
        }
        /**
         * Add meta description tag
         */
        if ($product->meta_description) {
            $description = strip_tags($product->meta_description);
            $this->view->headMeta()->setName('description', $description);
        }
        /**
         * Add title
         */
        if ($product->meta_title) {
            $this->view->headTitle($product->meta_title, 'SET');
        } else {
            $this->view->headTitle($product->name, 'SET');
        }

        /**
         * Format content
         */
        //$product->content = Tomato_Hook_Registry::getInstance()->executeFilter('product_product_Details_FormatContent', $product->content);

        /**
         * Add activate date
         * @since 2.0.4
         */
        if (null == $product->activate_date) {
            $product->activate_date = $product->created_date;
        }

        if (null == $categoryId) {
            $categoryId = $product->category_id;
        }

        $categoryModel = Rabbit_Model_Factory::getInstance()->setModule('category')->getCategoryModel();
        $category = $categoryModel->getById($categoryId);
        $parentCategories = $categoryModel->getParents($categoryId);
        /**
         * Increase product views
         */
        if ($product->status != 'drafted') {//!$preview &&
            $cookieName = '__rabbit_product_details_numviews';
            $viewed = false;
            if (!isset($_COOKIE[$cookieName])) {
                setcookie($cookieName, $productId, time() + 3600);
            } else {
                if (strpos($_COOKIE[$cookieName], $productId) === false) {
                    $cookie = $_COOKIE[$cookieName] . ',' . $productId;
                    setcookie($cookieName, $cookie);
                } else {
                    $viewed = true;
                }
            }
            if (!$viewed) {
                $productModel->increaseViews($productId);
            }
        }

        $this->view->assign('product', $product);
        $this->view->assign('category', $category);
        $this->view->assign('parentCategories', $parentCategories);
    }

    /**
     * Update Rating
     * @author TrongHM
     */
    public function rateAction() {
        $request = $this->getRequest();
        $this->_helper->getHelper('viewRenderer')->setNoRender();
        $this->_helper->getHelper('layout')->disableLayout();
        if ($request->isPost()) {
            $rate = $request->getPost('rate');
            $id = $request->getPost('idBox');
            $productModel = Rabbit_Model_Factory::getInstance()->setModule('product')->getProductModel();


            if ($productModel->rate($id, $rate)) {
                $this->_response->setBody('RESULT_OK');
            } else {
                $this->_response->setBody('RESULT_FAILED');
            }
        }
    }

    /** ------------------ Backend Action ----------------------------------- * */
    public function listAction() {
        $productModel = Rabbit_Model_Factory::getInstance()->setModule('product')->getProductModel();
        $request = $this->getRequest();
        $pageIndex = $request->getParam('pageIndex', 1);
        $perPage = 20;
        $offset = ($pageIndex - 1) * $perPage;

        /**
         * Build product search expression
         */
        $user = Zend_Auth::getInstance()->getIdentity();
        $params = null;
        $exp = array(
            'created_user_id' => $user->id,
        );

        /**
         * @since 2.0.8
         */
        $lang = $request->getParam('lang', Tomato_Config::getConfig()->web->lang);
        $productModel->setLang($lang);
        $this->view->assign('pageIndex', $pageIndex);
        if ($request->isPost()) {
            $id = $request->getPost('productId');
            $keyword = $request->getPost('keyword');
            $categoryId = $request->getPost('category');
            $findMineOnly = $request->getPost('findMyProducts');
            $purifier = new HTMLPurifier();

            if ($keyword) {
                $exp['keyword'] = $purifier->purify($keyword);
            }
            if ($id) {
                $exp['id'] = $purifier->purify($id);
            }
            if ($categoryId) {
                $exp['category_id'] = $categoryId;
            }
            if (null == $findMineOnly) {
                $exp['created_user_id'] = null;
            }
            if ($request->getPost('status')) {
                $exp['status'] = $request->getPost('status');
            }
            $params = rawurlencode(base64_encode(Zend_Json::encode($exp)));
        } else {
            $params = $request->getParam('q');
            if ($params != null) {
                $exp = rawurldecode(base64_decode($params));
                $exp = Zend_Json::decode($exp);
            } else {
                $params = rawurlencode(base64_encode(Zend_Json::encode($exp)));
            }
        }
//$products = $productModel->getAll();
        $products = $productModel->find($offset, $perPage, $exp);
        $numProducts = $productModel->count($exp);
        /**
         * Paginator
         */
        $paginator = new Zend_Paginator(new Tomato_Utility_PaginatorAdapter($products, $numProducts));
        $paginator->setCurrentPageNumber($pageIndex);
        $paginator->setItemCountPerPage($perPage);
        $this->view->assign('exp', $exp);
        $this->view->assign('products', $products);
        $this->view->assign('numProducts', $numProducts);
        $this->view->assign('paginator', $paginator);
        $this->view->assign('paginatorOptions', array(
            'path' => $this->view->url(array(), 'product_product_list'),
            'itemLink' => (null == $params) ? 'page-%d/' . $request->getParam('lang') . '/' : 'page-%d/' . $request->getParam('lang') . '?q=' . $params,
        ));
    }

    public function addAction() {

        $request = $this->getRequest();
        $productModel = Rabbit_Model_Factory::getInstance()->setModule('product')->getProductModel();


        /**
         * For translable source
         */
        /**
         * @since 2.0.8
         */
        $sourceId = $request->getParam('source_id');
        $sourceProduct = (null == $sourceId) ? null : $productModel->getById($sourceId);
        $this->view->assign('translatableData', (null == $sourceProduct) ? array() : $sourceProduct->getProperties());
        $this->view->assign('sourceProduct', $sourceProduct);
        $this->view->assign('lang', $request->getParam('lang'));

        if ($request->isPost()) {
            $user = Zend_Auth::getInstance()->getIdentity();
            $productImages = $request->getPost('productImages');
            $imageUrls = Zend_Json::decode(stripslashes($productImages));

            $product = new Product_Models_Entities_Product(array(
                        'category_id' => $request->getPost('category_id'),
                        'name' => strip_tags($request->getPost('name')),
                        'slug' => $request->getPost('slug'),
                        'description' => $request->getPost('description'),
                        'specification' => $request->getPost('specification'),
                        'price' => $request->getPost('price'),
                        'demo_url' => $request->getPost('demo_url'),
                        'thumbnail' => $request->getPost('thumbnail'),
                        'featured' => $request->getPost('featured'),
                        'attachment' => $request->getPost('attachment'),
                        'allow_comment' => $request->getPost('allow_comment', 0),
                        'created_date' => date('Y-m-d H:i:s'),
                        'created_user_id' => $user->id,
                        'created_user_name' => $user->username,
                        'author' => strip_tags($request->getPost('author')),
                        'status' => $request->getPost('status'),
                        'language' => $request->getPost('language'),
                        'attachment' => $request->getPost('attachment'),
                        'meta_title' => strip_tags($request->getPost('meta_title')),
                        'meta_description' => strip_tags($request->getPost('meta_description')),
                        'meta_keywords' => strip_tags($request->getPost('meta_keywords')),
                    ));
            if (null != $imageUrls) {
                $product->image_original = $imageUrls['original'];
                $product->image_square = $imageUrls['square'];
                $product->image_thumbnail = $imageUrls['thumbnail'];
                $product->image_small = $imageUrls['small'];
                $product->image_crop = $imageUrls['crop'];
                $product->image_medium = $imageUrls['medium'];
                $product->image_large = $imageUrls['large'];
            }

            if ($request->getPost('status') == 'actived') {
                $product->activate_user_name = $user->username;
                $product->activate_user_id = $user->id;
                $product->activated_date = date('Y-m-d H:i:s');
            }

            $id = $productModel->add($product);

            if ($id) {
                /**
                 * Add translation relation
                 */
                $source = Zend_Json::decode($request->getPost('sourceItem', '{"id": "", "language": ""}'));

                $translationModel = Rabbit_Model_Factory::getInstance()->setModule('core')->getTranslationModel();
                $translationModel->add(new Core_Models_Entities_Translation(array(
                            'item_id' => $id,
                            'item_class' => get_class($product),
                            'source_item_id' => ('' == $source['id']) ? $id : $source['id'],
                            'language' => $product->language,
                            'source_language' => ('' == $source['language']) ? null : $source['language'],
                        )));

                $this->_helper->getHelper('FlashMessenger')
                        ->addMessage('success:' . $this->view->translate('product_add_success'));
                $this->_redirect($this->view->serverUrl() . $this->view->url(array(), 'product_product_list'));
            } else {
                $this->_helper->getHelper('FlashMessenger')
                        ->addMessage('error:' . $this->view->translate('product_add_error'));
            }
        }
    }

    public function editAction() {
        $request = $this->getRequest();
        $productId = $request->getParam('id');
        $productModel = Rabbit_Model_Factory::getInstance()->setModule('product')->getProductModel();


        $product = $productModel->getById($productId);


        if (null == $product) {
            throw new Exception('Not found product with id of ' . $productId);
        }

        $this->view->assign('product', $product);
        $this->view->assign('productImages', Zend_Json::encode(array(
                    'original' => $product->image_original,
                    'square' => $product->image_square,
                    'thumbnail' => $product->image_thumbnail,
                    'small' => $product->image_small,
                    'crop' => $product->image_crop,
                    'medium' => $product->image_medium,
                    'large' => $product->image_large,
                )));
        $sourceProduct = $productModel->getSource($product);
        $this->view->assign('sourceProduct', $sourceProduct);

        if ($request->isPost()) {
            $user = Zend_Auth::getInstance()->getIdentity();
            $productImages = $request->getPost('productImages');
            $imageUrls = Zend_Json::decode(stripslashes($productImages));

            $params = array(
                'id' => $product->id,
                'category_id' => $request->getPost('category_id'),
                'name' => strip_tags($request->getPost('name')),
                'slug' => $request->getPost('slug'),
                'description' => $request->getPost('description'),
                'specification' => $request->getPost('specification'),
                'price' => $request->getPost('price'),
                'demo_url' => $request->getPost('demo_url'),
                'featured' => $request->getPost('featured'),
                'allow_comment' => $request->getPost('allow_comment', 0),
                'modified_date' => date('Y-m-d H:i:s'),
                'modified_user_id' => $user->id,
                'modified_user_name' => $user->username,
                'author' => strip_tags($request->getPost('author')),
                'status' => $request->getPost('status'),
                'language' => $request->getPost('language'),
                'attachment' => $request->getPost('attachment'),
                'meta_title' => strip_tags($request->getPost('meta_title')),
                'meta_description' => strip_tags($request->getPost('meta_description')),
                'meta_keywords' => strip_tags($request->getPost('meta_keywords')),
            );

            if (null != $imageUrls) {
                $params['image_original'] = $imageUrls['original'];
                $params['image_square'] = $imageUrls['square'];
                $params['image_thumbnail'] = $imageUrls['thumbnail'];
                $params['image_small'] = $imageUrls['small'];
                $params['image_crop'] = $imageUrls['crop'];
                $params['image_medium'] = $imageUrls['medium'];
                $params['image_large'] = $imageUrls['large'];
            }
            if ($request->getPost('status') == 'actived') {
                $params['activate_user_name'] = $user->username;
                $params['activate_user_id'] = $user->id;
                $params['activated_date'] = date('Y-m-d H:i:s');
            }

            if ($productModel->edit($params)) {
                $this->_helper->getHelper('FlashMessenger')
                        ->addMessage('success:' . $this->view->translate('product_edit_success'));
                $this->_redirect($this->view->serverUrl() . $this->view->url(array('id' => $productId), 'product_product_edit'));
            } else {
                $this->_helper->getHelper('FlashMessenger')
                        ->addMessage('error:' . $this->view->translate('product_edit_error'));
            }
        }
    }

    /**
     * Delete product
     *
     * @return void
     */
    public function deleteAction() {
        $this->_helper->getHelper('layout')->disableLayout();
        $this->_helper->getHelper('viewRenderer')->setNoRender();

        $request = $this->getRequest();
        $result = 'RESULT_ERROR';
        if ($request->isPost()) {
            $id = $request->getPost('id');
            $ids = array();
            if (is_numeric($id)) {
                $ids[] = $id;
            } else {
                $ids = Zend_Json::decode($id);
            }

            $productModel = Rabbit_Model_Factory::getInstance()->setModule('product')->getProductModel();

            foreach ($ids as $productId) {
                $product = $productModel->getById($productId);
                if ($product != null) {
                    if ('deleted' == $product->status) {
                        if ($productModel->delete($productId))
                            $result = 'RESULT_OK';

                        /**
                         * @since 2.0.8
                         */
//                        $translationDao = Rabbit_Model_Factory::getInstance()->setModule('core')->getTranslationDao();
//                        $translationDao->setDbConnection($conn);
//                        $translationDao->delete($productId, get_class($product));
                    } else {
                        if ($productModel->updateStatus($productId, 'deleted'))
                            $result = 'RESULT_OK';;
                    }
                }
            }
        }
        $this->getResponse()->setBody($result);
    }

    /**
     * Check product name exist or not
     *
     * @return void
     */
    public function checkAction() {
        $this->_helper->getHelper('viewRenderer')->setNoRender();
        $this->_helper->getHelper('layout')->disableLayout();

        $request = $this->getRequest();
        $value = $request->getParam('name');



        $existed = false;
        if ($value != null) {
            $productModel = Rabbit_Model_Factory::getInstance()->setModule('product')->getProductModel();
            $existed = $productModel->exist($value);
        }
        ($existed == true) ? $this->getResponse()->setBody('false') : $this->getResponse()->setBody('true');
    }

    public function searchAction() {
        $this->view->headTitle($this->view->translate('product_search_page_title'));
        $productModel = Rabbit_Model_Factory::getInstance()->setModule('product')->getProductModel();
        $request = $this->getRequest();
        $pageIndex = $request->getParam('pageIndex', 1);
        $perPage = 20;
        $offset = ($pageIndex - 1) * $perPage;
        $exp = array(
            'status' => 'actived',
        );
        if ($request->isPost()) {
            $keyword = $request->getParam('keyword');
            $categoryId_1 = $request->getParam('category_id_1');
            $categoryId_2 = $request->getParam('category_id_2');
            if ($categoryId_2)
                $exp['category_id'] = $categoryId_2;
            else if ($categoryId_1)
                $exp['category_id'] = $categoryId_1;
            if ($keyword)
                $exp['keyword'] = $keyword;

            $products = $productModel->find($offset, $perPage, $exp);
            $numProducts = $productModel->count($exp);
            /**
             * Paginator
             */
            if ($numProducts) {
                $paginator = new Zend_Paginator(new Tomato_Utility_PaginatorAdapter($products, $numProducts));
                $paginator->setCurrentPageNumber($pageIndex);
                $paginator->setItemCountPerPage($perPage);
                $this->view->assign('exp', $exp);
                $this->view->assign('products', $products);
                $this->view->assign('numProducts', $numProducts);
                $this->view->assign('paginator', $paginator);
                $this->view->assign('paginatorOptions', array(
                    'path' => $this->view->url(array(), 'product_product_search'),
                    'itemLink' => 'page-%d',
                ));
            }else{
                $this->_helper->getHelper('FlashMessenger')
                    ->addMessage('error:' . $this->view->translate('product_search_no_result'));
            }
        } else {
            $this->_helper->getHelper('FlashMessenger')
                    ->addMessage('error:' . $this->view->translate('product_search_must_search_first'));
        }
        
    }
}

?>
